package org.gongliang.common.scan;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.DisabledAccountException;
import org.gongliang.common.base.Result;
import org.gongliang.common.exception.BussinessException;
import org.gongliang.common.exception.ExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * @author 龚亮
 * @date 2016年11月12日 下午3:19:56
 */
//@ControllerAdvice
public class GlobalExceptionHandler {

	public static final Logger logger = LoggerFactory
			.getLogger(KExceptionHandler.class);

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(BussinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
	public Result notFount(BussinessException e) {
		logger.error("业务异常:", ExceptionUtils.getStackTrace(e));
		return new Result(e.getErrCode(), e.getErrMsg(), Result.STATE_ERROR);
    }

    /**
     * 用户未登录
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String unAuth(AuthenticationException e) {
		logger.error("用户未登陆：", ExceptionUtils.getStackTrace(e));
		return "login";
    }

    /**
     * 账号被冻结
     */
    @ExceptionHandler(DisabledAccountException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String accountLocked(DisabledAccountException e, Model model) {
		logger.error("账号被冻结：", ExceptionUtils.getStackTrace(e));
		return "login";
    }

    /**
	 * 账号或密码错误
	 */
    @ExceptionHandler(CredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
	public String credentials(CredentialsException e) {
		logger.error("账号或密码错误：", ExceptionUtils.getStackTrace(e));
		return "login";
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
	public Result sysError(RuntimeException e) {
		logger.error("运行时异常:", ExceptionUtils.getStackTrace(e));
		return new Result(ExceptionEnum.SERVER_ERROR, Result.STATE_ERROR);
    }

}
